package com.minio.learning.springminio.handler;

import com.minio.learning.springminio.exception.ServiceException;
import com.minio.learning.springminio.resp.CommonResult;
import com.minio.learning.springminio.util.StringUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.Objects;

/**
 * 全局异常处理器
 *
 * @author YanXxx
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public CommonResult<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                               HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return CommonResult.error(e.getMessage());
    }



    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public CommonResult<?> handleServiceException(ServiceException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生业务异常.",requestURI, e);
        Integer status = e.getStatus();
        return StringUtils.isNotNull(status) ? CommonResult.build(status, e.getMessage()) : CommonResult.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return CommonResult.error("系统异常,请联系管理员！");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public CommonResult<?> handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return CommonResult.error(message);
    }


    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return CommonResult.error(message);
    }

    /**
     * json 序列化异常
     *
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public CommonResult<?> handlerJsonParseException(HttpMessageNotReadableException e, HttpServletRequest request) {
        String message;
        String msg = "JSON parse error:";
        if (Objects.requireNonNull(e.getMessage()).contains(msg)) {
            message = "JSON parse error,请检查入参";
        } else {
            String requestURI = request.getRequestURI();
            log.error("请求地址'{}',发生系统异常.", requestURI, e);
            message = e.getMessage();
        }
        return CommonResult.error(message);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public CommonResult<?> handleConstraintViolationException(ConstraintViolationException e) {
        log.info(e.getMessage(), e);
        return CommonResult.error(e.getMessage());
    }

}
